<?php 

define('TL_MODE', 'FE');
require('system/initialize.php');
session_start();

class ecpaypal extends 	Controller
{
	private $inCode = '';
	private $strError = '';
	
	public function __construct()
	{
		parent::__construct();
		header('Cache-Control: no-store, no-cache, must-revalidate');
		
		include_once(TL_ROOT.'/templates/ecpaypal/defined.php');
	}
	
	public function revieworder()
	{
		if (!$_SESSION['cart'])
			echo '<div id="product_detail"><strong>The cart is empty.</strong></div>';
        
		$items = $_SESSION['cart'];
		foreach ($items as $key => $item) {
			$totalPrice += number_format(floatval($item['price']*$item['quantity'])+$item['gwPrice'], 2, '.', '');
		}
		if (!$_SESSION['ORDER']['totalPrice'])
			$_SESSION['ORDER']['totalPrice'] = $totalPrice;
		
        $shopname = 'daftshopping'; //商店名称作为商品名称
        $paymentAmount = (float)$totalPrice;  
        $serverName = $_SERVER['SERVER_NAME'];
        $serverPort = $_SERVER['SERVER_PORT'];
        $url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);            
        $paymentType= 'Sale';
        
		$this->import("Database");
		$objSession = $this->Database->prepare("SELECT * FROM tl_session WHERE hash=? AND name=?")
									->execute($_COOKIE['FE_USER_AUTH'], 'FE_USER_AUTH');
		$obj_member = $this->Database->prepare("SELECT * FROM tl_member WHERE id=?")
									->execute($objSession->pid);
		$preferred = ($obj_member->cur)?$obj_member->cur:$_COOKIE['DAFT_CURRENCY'];
		if (!$preferred){
			$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency` WHERE `is_default`=1")
											->execute(time());
			
			$currencyCodeType = $obj_currency->iso_code;
		}else{
			$currencyCodeType = $preferred;
		}		
        
		if ($currencyCodeType == 'RMB')
			$currencyCodeType = "USD";
		
		setcookie("PAY_CURRENCY", $currencyCodeType);
        $returnURL = urlencode($this->Environment->base."ecpaypal.php?action=returnUrl");
        $cancelURL = urlencode($this->Environment->base."shoppingcart.html");                
        #$nvpstr="&L_NAME=p1&L_AMT=0.1&L_QTY0=2&L_NAME1=p2&L_AMT2=0.2&L_QTY2=2"."&Amt=".$paymentAmount."&PAYMENTACTION=".$paymentType."&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType;
        $nvpstr="&L_NAME0=".$shopname."&L_AMT0=".$paymentAmount."&L_QTY0=1"."&Amt=".$paymentAmount."&PAYMENTACTION=".$paymentType."&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType;
        $resArray = $this->hash_call("SetExpressCheckout",$nvpstr);
		$_SESSION['reshash'] = $resArray;       
        $ack = strtoupper($resArray["ACK"]);
		
        if($ack=="SUCCESS")
        {
            $token = urldecode($resArray["TOKEN"]);
            $payPalURL = PAYPAL_URL.$token;
            echo "<script>window.location='".$payPalURL."'</script>";
            exit;
        }
        else
        {
            echo 'Waiting for amomment!';exit;
        }
	}
	
	public function returnUrl()
    {
        if (!$_SESSION['cart'])
			echo '<div id="product_detail"><strong>The cart is empty.</strong></div>';
			
        $token = $_SESSION['reshash']['TOKEN'];
        $nvpstr = "&TOKEN=".$token."&subject=".AIP_SUBJECT;
        $resArray = $this->hash_call("GetExpressCheckoutDetails",$nvpstr);
		$_SESSION['reshash'] = $resArray;
        $_SESSION['paypal_params'] = $_REQUEST;
        $ack = strtoupper($resArray["ACK"]);
		
        if($ack=="SUCCESS")
        {
            //unset( $_SESSION['reshash']);
            include_once(TL_ROOT . '/system/config/countries.php');
			$country_code = array_search($resArray['SHIPTOCOUNTRYNAME'], $countries);
			if ($country_code)
			{
				$this->import('Database');
				$objSession = $this->Database->prepare("SELECT * FROM tl_session WHERE hash=? AND name=?")
								 ->execute($_COOKIE['FE_USER_AUTH'], 'FE_USER_AUTH');
				
				/** 校验信息是否存在 **/
				if ($country_code == 'cn')
				{
					$obj_state = $this->Database->prepare("SELECT * FROM `china_province` WHERE `province_en`=? OR `province_zh`=?")
												->execute($resArray['SHIPTOSTATE']);
					if ($obj_state->numRows > 0)
					{
						$resArray['SHIPTOSTATE'] = $obj_state->id;
					}
					
					$obj_city = $this->Database->prepare("SELECT * FROM `china_city` WHERE `city_en`=? OR `city_zh`=?")
												->execute($resArray['SHIPTOCITY']);
					if ($obj_city->numRows > 0)
					{
						$resArray['SHIPTOCITY'] = $obj_city->id;
					}
				}
				
				$obj_address_book = $this->Database->prepare("SELECT `id` FROM `tl_address_book` WHERE `uid`=? AND `firstname`=? AND `lastname`=? AND `country`=? AND `state`=? AND `city`=? AND `street`=? AND `postcode`=?")
													->execute($objSession->pid,$resArray['FIRSTNAME'],$resArray['LASTNAME'],$country_code,$resArray['SHIPTOSTATE'],$resArray['SHIPTOCITY'],$resArray['SHIPTOSTREET'],$resArray['SHIPTOZIP']);				
				/** end **/
				
				if ($obj_address_book->numRows == 0)
				{
					$obj_address_book = $this->Database->prepare("INSERT INTO tl_address_book (`uid`,`firstname`,`lastname`,`country`,`state`,`city`,`street`,`email`,`postcode`) VALUES(?,?,?,?,?,?,?,?,?)")
														->execute($objSession->pid,$resArray['FIRSTNAME'],$resArray['LASTNAME'],$country_code,$resArray['SHIPTOSTATE'],$resArray['SHIPTOCITY'],$resArray['SHIPTOSTREET'],$resArray['EMAIL'],$resArray['SHIPTOZIP']);
					$_SESSION['ORDER']['address_shipping'] = $obj_address_book->insertId;
				}
				else
				{
					$_SESSION['ORDER']['address_shipping'] = $obj_address_book->id;
				}
				
				$_SESSION['ORDER']['is_paypal_fast'] = true;
				header("Location: ".$this->Environment->base."address.html");exit;
			}           
        } 
        else  
        {
            echo 'Waiting for amomment!';exit;
        }
    }
	
	private function hash_call($methodName,$nvpStr)
	{
        $API_UserName = PAYPAL_MEMBERID;
        $API_Password = PAYPAL_PASSWORD;
        $API_Signature = PAYPAL_SIGNATURE;
        $API_Endpoint = API_ENDPOINT;
        $version = VERSION;
        /*
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST, 1);*/
        //if(USE_PROXY)
       // curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
        $nvpreq = "METHOD=".urlencode($methodName)."&VERSION=".urlencode($version)."&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature).$nvpStr;
        #print_r($nvpreq);exit;
		$request = new Request();
		$request->send(API_ENDPOINT,$nvpreq,'POST');
		$nvpResArray = $this->deformatNVP($request->response);
        $nvpReqArray = $this->deformatNVP($nvpreq);
		$_SESSION['nvpReqArray'] = $nvpReqArray;
		
		return $nvpResArray;
	}
	
	private function deformatNVP($nvpstr)
    {
        $intial=0;
        $nvpArray = array();
        while(strlen($nvpstr))
        {
            $keypos= strpos($nvpstr,'=');
            $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
            $keyval=substr($nvpstr,$intial,$keypos);
            $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
            $nvpArray[urldecode($keyval)] =urldecode( $valval);
            $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
        }
        return $nvpArray;
    }
}

session_start();

$ec_paypal	= new ecpaypal();
$action = $_GET['action'];
if (method_exists($ec_paypal, $action))
{
	$ec_paypal->$action();
}